package Thread;


/**
 * count++经历的步骤
 * 将count读入到寄存器中
 * count在寄存器中进行+1操作
 * count从寄存器返回到呢
 */

//因为count++不具有原子性 , 因此在多线程中会出现线程安全(也与抢占性有关)
public class Test22 {
    static int count = 0;
    public void add(){
        synchronized (this){
            count++;
        }
    }
    public static void main2(String[] args) throws InterruptedException {
        Test22 test22 = new Test22();
        Thread t1 = new Thread(()->{
            for(int i = 0;i<5000;i++){
                test22.add();
            }
        });
        Thread t2 = new Thread(()->{
            for(int i = 0;i<5000;i++){
                test22.add();
            }
        });
        t1.start();
        t2.start();
        Thread.sleep(2000);
        System.out.println(count);
    }
    public static void main1(String[] args) throws InterruptedException {
//        Test22 test22 = new Test22();
        Thread t1 = new Thread(()->{

                for(int i = 0;i<5000;i++){
                    count++;
                }


        });
        Thread t2 = new Thread(()->{
            for(int i = 0;i<5000;i++){
                count++;
            }
        });
        t1.start();
        t2.start();
        Thread.sleep(2000);
        System.out.println(count);
    }
}
